package com.zhaorl.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zhaorl.domain.LoginUser;
import com.zhaorl.domain.User;
import com.zhaorl.domain.result.ResponseResult;
import com.zhaorl.service.LoginService;
import com.zhaorl.utils.JwtUtil;
import com.zhaorl.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @Description 登录退出相关业务层
 * @Author zhaorl
 * @Date 2023/3/28 16:11
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    /**
     * @description 用户登录实现层
     * @param user
     * @return ResponseResult
     * @author zhaorl
     * @date 2023/3/28 16:16
     */
    @Override
    public ResponseResult login(User user) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        System.out.println(authenticate);
        if (Objects.isNull(authenticate)){
            throw new RuntimeException("用户名或密码错误");
        }
        // 获取LoginUser对象
        LoginUser loginUser = (LoginUser)authenticate.getPrincipal();
        // 获取用户id 根据用户id生成token
        String userId = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userId);
        // 将authenticate内的LoginUser存入redis
        redisCache.setCacheObject("login:" + userId,loginUser,12, TimeUnit.HOURS);
        Map<String,Object> map = new HashMap<>();
        map.put("token",jwt);
        return new ResponseResult(200,"登录成功",map);
    }

    /**
     * 退出登录
     * @return
     */
    @Override
    public ResponseResult logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser)authentication.getPrincipal();
        // 用户id
        Long userId = loginUser.getUser().getId();
        redisCache.deleteObject("login:" + userId);
        return new ResponseResult(200,"退出登录成功");
    }
}
